package com.youuvs.org.service.impl;

import com.youuvs.basic.service.impl.BaseServiceImpl;
import com.youuvs.org.domian.Department;
import com.youuvs.org.mapper.DepartmentMapper;
import com.youuvs.org.query.DepartmentQuery;
import com.youuvs.org.service.IDepartmentService;
import com.youuvs.basic.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    @Transactional
    public void insert(Department department) {
        //从xml中获取自增主键
        departmentMapper.insert(department);
        //先判断是否有上级部门
       /* if (department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else{
            Long parent_id = department.getParent_id();
            Department parentDepartment = departmentMapper.findById(parent_id);
            department.setDirPath(parentDepartment.getDirPath()+"/"+department.getId());
        };*/
        update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //先判断是否有上级部门
        if (department.getParent()==null || department.getParent().getId()==null){
            department.setDirPath("/"+department.getId());
        }else{
            Long parent_id = department.getParent_id();
            Department parentDepartment = departmentMapper.findById(parent_id);
            department.setDirPath(parentDepartment.getDirPath()+"/"+department.getId());
        };
        departmentMapper.update(department);
    }




    @Override
    public List<Department> getTree() {
        //查询出所有部门
        List<Department> all = departmentMapper.findAll();
       HashMap<Long,Department> map = new HashMap<>();
        //遍历所有部门
        for (Department department : all) {
            //将每个部门放入map
                map.put(department.getId(),department);
        }
        ArrayList<Department> deptTree = new ArrayList<>();
        for (Department department : all) {
            if(department.getParent_id()==null){
                //这是顶级部门
                deptTree.add(department);
            }else{
                //非顶级部门,拿到他的上级部门id
                Long parent_id = department.getParent_id();
                //拿到上级部门信息
                Department parentDepartment = map.get(parent_id);
                //将该部门放到上级部门的children中
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;

    }


}
